﻿using System.Collections.Generic;
using ICSharpCode.AvalonEdit.Folding;
using QueryResource.Analytic;

namespace SQLQuery.UI.SQLEdit
{
    class SqlFoldingStrategy : AbstractFoldingStrategy
    {
        public override IEnumerable<NewFolding> CreateNewFoldings(ICSharpCode.AvalonEdit.Document.TextDocument document, out int firstErrorOffset)
        {
            firstErrorOffset = -1;
            List<NewFolding> newFoldings = new List<NewFolding>();
            /* 
             */
            Stack<int> startOffsets = new Stack<int>();
            int lastNewLineOffset = 0;

            for (int i = 0; i < document.TextLength -1; i++)
            {
                char c = document.GetCharAt(i);
                string str = document.GetText(i,2);
                if (str == "/*")
                {
                    startOffsets.Push(i);
                }
                else if (str == "*/" && startOffsets.Count > 0)
                {
                    int startOffset = startOffsets.Pop();
                    // don't fold if opening and closing brace are on the same line
                    if (startOffset < lastNewLineOffset)
                    {
                        newFoldings.Add(new NewFolding(startOffset, i + 2));
                    }
                }
                else if (c == '\n' || c == '\r')
                {
                    lastNewLineOffset = i + 1;
                }
            }
            newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
            return newFoldings;
        }

        public override IEnumerable<NewFolding> CreateNewFoldings(string text, out int firstErrorOffset)
        {
            firstErrorOffset = -1;

            List<NewFolding> newFoldings = new List<NewFolding>();
            try
            {
                Dictionary<int, int> dic = AnalyFactory.GetAnalytic().GetFolding(text);
                foreach (int key in dic.Keys)
                {
                    int end = dic[key];
                    if (text.Length > end)
                    {
                        end++;
                    }
                    newFoldings.Add(new NewFolding(key, end));
                }
            }
            catch { }
            newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
            return newFoldings;
        }

    }
}
